package model.factories.misc;

import java.util.Map;
import java.util.Scanner;
import java.util.regex.Pattern;
import model.Interpreter;
import model.SyntaxErrorException;
import model.commands.Command;
import model.commands.misc.ToCommand;
import model.factories.CommandFactory;


/**
 * A class responsible for creating ToCommand objects.
 * 
 * @author Erick Gonzalez
 */
public class ToCommandFactory extends CommandFactory {
    /**
     * A pattern that matches TO command keywords.
     */
    private final Pattern myToPattern = Pattern.
            compile(getInterpreter().getLanguage().getString("ToCommandPattern"));

    /**
     * 
     * @param interpreter an interpreter
     */
    public ToCommandFactory (Interpreter interpreter) {
        super(interpreter);
    }

    @Override
    public Pattern patternToMatch () {
        return myToPattern;
    }

    @Override
    public Command createCommand (Scanner commandReader,
                                  Map<String, Integer> variables) throws SyntaxErrorException {
        // get rid of the 'TO' keyword
        commandReader.next();

        String commandName = commandReader.next();

        StringBuilder commandInfoBuilder = new StringBuilder();
        buildCommandInfo(commandReader, commandInfoBuilder);
        commandInfoBuilder.append(" ");
        buildCommandInfo(commandReader, commandInfoBuilder);

        return new ToCommand(getInterpreter(), commandName, commandInfoBuilder.toString());
    }

    private void buildCommandInfo (Scanner commandReader,
                                   StringBuilder commandInfoBuilder) {
        while (!commandReader.hasNext("]")) {
            commandInfoBuilder.append(commandReader.next() + " ");
        }
        // add the closing bracket
        commandInfoBuilder.append(commandReader.next());
    }
}
